'use strict';

const Fs = require('fs');
const Path = require('path');
const uuidv4 = require('uuid/v4');
const crypto = require('crypto');

const Service = require('egg').Service;

class CodingService extends Service {
  async base64() {
    const data = this.ctx.w_body();
    // eslint-disable-next-line default-case
    switch (data.type) {
      case 'encode':
        return new Buffer.from(data.code).toString('base64');
      case 'decode':
        return new Buffer.from(data.code, 'base64').toString();
      case 'hexEncode':
        return new Buffer.from(data.code, 'base64').toString('hex');
      case 'hexDecode':
        return new Buffer.from(data.code, 'hex').toString('utf8');
    }
  }
  async imgToBase64() {
    const bitmap = Fs.readFileSync(this.ctx.w_body().imageUrl);
    return new Buffer.from(bitmap).toString('base64');
  }
  async base64ToImg() {
    // 获取时间
    const datePath = this.ctx.helper.formatDate(new Date(), 'YYYY/MM/DD/HH');
    const path = Path.resolve(__dirname, `../public/up-image/${datePath}`);
    if (!Fs.existsSync(path)) {
      Fs.mkdirSync(path, {
        recursive: true,
      });
    }
    const imgPath = Path.resolve(path, uuidv4());
    Fs.writeFileSync(imgPath, new Buffer.from(this.ctx.w_body().imageData, 'base64'));
    return imgPath.split('app')[1];
  }
  async md5() {
    const { input, type } = this.ctx.w_body();
    const hash = crypto.createHash(type);
    hash.update(input);
    return hash.digest('hex');
  }
  async hmac() {
    const { input, type, key } = this.ctx.w_body();
    const hash = crypto.createHash(type, key);
    hash.update(input);
    return hash.digest('hex');
  }
  async aes() {
    const { input, key, type } = this.ctx.w_body();
    const iv = Buffer.from('FnJL7EDzjqWjcaY9', 'utf8');

    // 加密
    function genSign(src, key, iv) {
      let sign = '';
      const cipher = crypto.createCipheriv('aes-128-cbc', key, iv);
      sign += cipher.update(src, 'utf8', 'hex');
      sign += cipher.final('hex');
      return sign;
    }

    // 解密
    function deSign(sign, key, iv) {
      let src = '';
      const cipher = crypto.createDecipheriv('aes-128-cbc', key, iv);
      src += cipher.update(sign, 'hex', 'utf8');
      src += cipher.final('utf8');
      return src;
    }

    return type === 'encode' ? genSign(input, key, iv) : deSign(input, key, iv);
  }
}

module.exports = CodingService;
